<template>
  <div class="receive-page">
    <!-- 顶部导航栏 -->
    <div class="nav-header">
      <img src="../assets/icons/back.svg" class="back-icon" @click="goBack" />
    </div>
    
    <!-- 标题容器 -->
    <div class="title-container">
      <h1 class="page-title">代取记录</h1>
    </div>

    <!-- 列表容器结构与Receive相同 -->
    <div class="history-list" ref="listContainer">
      <div class="content-wrapper" ref="contentWrapper">
        <div class="cards-container" :style="{ transform: `translateY(${translateY}px)` }">
          <div class="refresh-area">
            {{ refreshText }}
          </div>
          
          <div v-if="isEmpty" class="empty-state">
            暂无代取记录
          </div>
          
          <history-card
            v-else
            v-for="item in historyItems" 
            :key="item.order_id"
            :orderData="item"
            :cardType="'pickup'"
            @buttonClick="handleCardAction"
            @cardClick="handleCardClick"  
            @showConfirmDialog="showConfirmDialog"
            @showFinishDialog="showFinishDialog"
          />

          <div class="loading-area" ref="loadingArea">
            {{ loadingText }}
          </div>
        </div>
      </div>
    </div>

    <!-- 添加弹窗组件 -->
    <!-- 确认取消弹窗 -->
    <div v-if="dialogState.showConfirm" class="dialog-overlay">
      <div class="dialog-content">
        <h3>确认取消代取？</h3>
        <p>取消后将无法恢复，是否确认？</p>
        <div class="dialog-buttons">
          <button @click="confirmCancel" class="btn-action complete">确认</button>
          <button @click="closeDialog" class="btn-action">取消</button>
        </div>
      </div>
    </div>

    <!-- 完成配送弹窗 -->
    <div v-if="dialogState.showFinishDialog" class="dialog-overlay">
      <div class="dialog-content">
        <h3>确认完成配送？</h3>
        <p>是否确认完成配送？</p>
        <div class="dialog-buttons">
          <button @click="finishPickup" class="btn-action complete">确认</button>
          <button @click="closeDialog" class="btn-action">取消</button>
        </div>
      </div>
    </div>

    <!-- 成功提示弹窗 -->
    <div v-if="dialogState.showSuccess" class="dialog-overlay">
      <div class="dialog-content">
        <h1>{{ dialogState.successMessage }}</h1>
        <button @click="closeSuccessDialog" class="btn-action complete">确定</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, onBeforeUnmount, nextTick, computed } from 'vue'
import { useRouter } from 'vue-router'
import HistoryCard from '@/component/HistoryCard.vue'
import defaultCardImage from '@/assets/imgTest/cardData.jpg'
import axios from 'axios'

const router = useRouter()
const listContainer = ref(null)
const contentWrapper = ref(null)
const isLoading = ref(false)
const loadingText = ref('上滑加载更多')
const translateY = ref(0)
const scrollPosition = ref(0)
let startY = 0
let currentY = 0

// 修改缓存键名
const CACHE_KEY = 'pickupHistory' // 区分与委托历史的存储
const CACHE_EXPIRY_TIME = 1 * 60 * 1000
const lastUpdateTime = ref(0)

// 获取本地存储的代取记录
const getLocalHistoryItems = () => {
  const cached = localStorage.getItem(CACHE_KEY)
  if (cached) {
    const { data, timestamp } = JSON.parse(cached)
    lastUpdateTime.value = timestamp
    return data
  }
  return []
}

// 保存代取记录到本地存储
const saveLocalHistoryItems = (items) => {
  const timestamp = Date.now()
  localStorage.setItem(CACHE_KEY, JSON.stringify({
    data: items,
    timestamp
  }))
  lastUpdateTime.value = timestamp
}

// 检查数据是否需要更新
const needsUpdate = () => {
  return Date.now() - lastUpdateTime.value > CACHE_EXPIRY_TIME
}

// 添加分页相关变量
const currentPage = ref(1)
const hasMore = ref(true)

// 替换模拟API调用为真实API调用
const fetchOrders = async (page = 1) => {
  try {
    const currentUser = JSON.parse(localStorage.getItem('user'));
    const userId = currentUser ? currentUser.uid : null;

    if (!userId) {
      console.error('未找到用户ID');
      return { success: false, data: [] };
    }

    const response = await axios.get('api/auth/receive_order', {
      params: { 
        page: page 
      },
      headers: {
        'Content-Type': 'application/json',
        'Authorization': localStorage.getItem('token')
      }
    });

    if (response.data.code === 0) {
      // 更新状态映射以匹配数据库枚举
      const statusMap = {
        'PUBLISHED': 0,    // 已发布
        'PENDING': 1,      // 配送中
        'ARGUE': 2,        // 争议中
        'COMPLETED': 3,    // 已完成
        'COMPLETED_REQUEST': 4,  // 完成请求（显示为已完成）
        'CANCELLED': 5,    // 已取消
        'CANCELLED_REQUEST': 6   // 取消请求（显示为已取消）
      };

      // 转换返回的数据格式
      const orders = response.data.data.orders.map(order => ({
        order_id: order.OrderID,
        s_uid: order.SUID,
        r_uid: order.RUID,
        pickup_type: order.PickupType,
        pickup_method: order.PickupMethod,
        pickup_address: order.PickupAddress,
        delivery_address: order.DeliveryAddress,
        size: order.Size,
        limit_time: new Date(order.LimitTime).getTime(),
        phone_number: order.PhoneNumber,
        remarks: order.Remarks,
        detail: order.Detail,
        total_amount: order.TotalAmount,
        status: statusMap[order.Status] ?? 0,
        created_at: new Date(order.CreatedAt).getTime(),
        completed_at: order.CompletedAt ? new Date(order.CompletedAt).getTime() : 0,
        star: order.Star,
        img: order.Img || defaultCardImage
      }));

      // 假设后端返回了是否有更多数据的标志
      const has_more = response.data.data.has_more || false;
      hasMore.value = has_more;
      
      return { success: true, data: orders };
    }
    
    return { success: false, data: [] };
  } catch (error) {
    console.error('获取委托历史失败:', error);
    return { success: false, data: [] };
  }
}

// 添加页面状态管理
const pageState = ref({
  currentPage: 1,
  hasMore: true,
  isFirstLoad: true
})

// 修改初始化函数
const initializeData = async () => {
  if (!pageState.value.isFirstLoad) return
  
  const result = await fetchOrders(1)
  if (result.success) {
    historyItems.value = result.data
    pageState.value.isFirstLoad = false
  } else {
    loadingText.value = '加载失败，请下拉刷新'
  }
}

// 存储代取记录数组
const historyItems = ref([])

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 修改卡片动作处理函数
const handleCardAction = ({ action, orderId }) => {
  switch(action) {
    case 'contact':
      console.log('联系委托人', orderId)
      break
    case 'cancel':
      showConfirmDialog({ orderId, status: 'cancel' })
      break
    case 'complete':
      showFinishDialog(orderId)
      break
  }
}

// 添加卡片点击处理函数
const handleCardClick = async ({ orderId }) => {
  try {
    const response = await axios.post(
      '/api/auth/order_detail',
      { order_id: parseInt(orderId) },
      {
        headers: {
          'Authorization': localStorage.getItem('token'),
          'Content-Type': 'application/json'
        }
      }
    )

    if (response.data.code === 0) {
      // 存储委托信息到 sessionStorage
      sessionStorage.setItem('currentDelegation', JSON.stringify(response.data.data))
      
      // 使用完整路径进行跳转，注意这里使用的是 delegation 而不是 delegation_r
      router.push(`/delegation/${orderId}?timestamp=${new Date().getTime()}`)
    } else {
      console.error('获取委托详情失败:', response.data.message)
    }
  } catch (error) {
    console.error('获取委托详情失败:', error)
  }
}

// 触摸处理逻辑
const handleTouchStart = (e) => {
  if (isLoading.value) return
  startY = e.touches[0].clientY
  currentY = startY
}

const handleTouchMove = (e) => {
  if (isLoading.value) return
  
  const container = listContainer.value
  const scrollTop = container.scrollTop
  const scrollHeight = container.scrollHeight
  const clientHeight = container.clientHeight
  currentY = e.touches[0].clientY
  const delta = currentY - startY

  // 处理下拉刷新（在顶部）
  if (scrollTop <= 0) {
    if (delta > 0) {
      const pullDistance = delta
      translateY.value = Math.min(pullDistance * 0.5, 80)

      if (pullDistance > 120) {
        refreshText.value = '释放立即刷新'
      } else {
        refreshText.value = '下拉刷新'
      }
      e.preventDefault()
      return
    }
  }

  // 处理上滑加载（在底部）
  if (scrollTop + clientHeight >= scrollHeight - 110) {
    if (delta < 0) {
      const pullDistance = Math.abs(delta)
      translateY.value = -Math.pow(pullDistance * 0.2, 0.8)
      
      if (pullDistance > 500) {
        loadingText.value = '释放立即加载'
      } else {
        loadingText.value = '上滑加载更多'
      }
      e.preventDefault()
    }
  }
}

const handleTouchEnd = async () => {
  if (isLoading.value) return

  if (translateY.value >= 60) {
    await handleRefresh()
  }
  else if (translateY.value <= -40) {
    await loadMore()
  }

  translateY.value = 0
}

// 修改刷新处理函数
const handleRefresh = async () => {
  if (isLoading.value) return
  
  try {
    isLoading.value = true
    refreshText.value = '刷新中...'
    
    // 重置页面状态
    pageState.value = {
      currentPage: 1,
      hasMore: true,
      isFirstLoad: false
    }
    
    const result = await fetchOrders(1)
    if (result.success) {
      historyItems.value = result.data
      refreshText.value = '刷新成功'
    } else {
      refreshText.value = '刷新失败'
    }
  } catch (error) {
    console.error('刷新失败:', error);
    refreshText.value = '刷新失败'
  } finally {
    await new Promise(resolve => setTimeout(resolve, 500))
    isLoading.value = false
    refreshText.value = '下拉刷新'
    translateY.value = 0
  }
}

// 修改加载更多函数
const loadMore = async () => {
  if (isLoading.value || !pageState.value.hasMore) return

  try {
    isLoading.value = true
    loadingText.value = '加载中...'
    
    const result = await fetchOrders(pageState.value.currentPage + 1)
    if (result.success) {
      if (result.data.length > 0) {
        historyItems.value = [...historyItems.value, ...result.data]
        pageState.value.currentPage += 1
        loadingText.value = '加载成功'
      } else {
        pageState.value.hasMore = false
        loadingText.value = '没有更多数据了'
      }
    } else {
      loadingText.value = '加载失败'
    }
    
    await new Promise(resolve => setTimeout(resolve, 500))
  } catch (error) {
    console.error('Failed to load more:', error)
    loadingText.value = '加载失败'
  } finally {
    isLoading.value = false
    translateY.value = 0
  }
}

// 空状态检查
const isEmpty = computed(() => historyItems.value.length === 0)

const refreshText = ref('下拉刷新')

// 添加弹窗状态管理
const dialogState = ref({
  showConfirm: false,
  showFinishDialog: false,
  showSuccess: false,
  successMessage: '',
  currentOrderId: null,
  currentStatus: null
})

// 显示确认弹窗
const showConfirmDialog = ({ orderId, status }) => {
  dialogState.value.showConfirm = true
  dialogState.value.currentOrderId = orderId
  dialogState.value.currentStatus = status
}

// 显示完成配送弹窗
const showFinishDialog = (orderId) => {
  dialogState.value.showFinishDialog = true
  dialogState.value.currentOrderId = orderId
}

// 关闭所有弹窗
const closeDialog = () => {
  dialogState.value.showConfirm = false
  dialogState.value.showFinishDialog = false
}

// 关闭成功提示弹窗
const closeSuccessDialog = () => {
  dialogState.value.showSuccess = false
  window.location.reload()
}

// 取消代取方法
const cancelPickup = async (orderId) => {
  try {
    const response = await axios.post('/api/auth/com-cancel-sender', 
      { order_id: parseInt(orderId) },
      {
        headers: {
          'Authorization': localStorage.getItem('token'),
          'Content-Type': 'application/json'
        }
      }
    )

    if (response.data.code === 0) {
      dialogState.value.showConfirm = false
      dialogState.value.successMessage = '取消配送成功'
      dialogState.value.showSuccess = true
    } else {
      alert(response.data.message || '取消配送失败')
    }
  } catch (error) {
    console.error('取消配送失败:', error)
    alert('取消配送失败，请重试')
  }
}

// 完成配送方法
const finishPickup = async () => {
  try {
    const response = await axios.post('/api/auth/finish_accept', 
      { order_id: parseInt(dialogState.value.currentOrderId) },
      {
        headers: {
          'Authorization': localStorage.getItem('token'),
          'Content-Type': 'application/json'
        }
      }
    )

    if (response.data.code === 0) {
      dialogState.value.showFinishDialog = false
      dialogState.value.successMessage = '完成配送成功'
      dialogState.value.showSuccess = true
    } else {
      alert(response.data.message || '完成配送失败')
    }
  } catch (error) {
    console.error('完成配送失败:', error)
    alert('完成配送失败，请重试')
  }
}

// 确认取消方法
const confirmCancel = () => {
  cancelPickup(dialogState.value.currentOrderId)
}

// 生命周期钩子
onMounted(async () => {
  await initializeData()
  
  const container = listContainer.value
  if (container) {
    container.addEventListener('touchstart', handleTouchStart, { passive: false })
    container.addEventListener('touchmove', handleTouchMove, { passive: false })
    container.addEventListener('touchend', handleTouchEnd)
  }
})

// 修正 onBeforeUnmount，移除不必要的缓存清除
  onBeforeUnmount(() => {
  // 不需要每次都清除缓存
  // localStorage.removeItem('pickupHistory') 
})

onUnmounted(() => {
  const container = listContainer.value
  if (container) {
    container.removeEventListener('touchstart', handleTouchStart)
    container.removeEventListener('touchmove', handleTouchMove)
    container.removeEventListener('touchend', handleTouchEnd)
  }
})
</script>

<style scoped>
.receive-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #ffffff;  /* 修改背景色为纯白 */
  position: fixed;  /* 添加固定定位 */
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.nav-header {
  height: 61px;
  background: #ffffff;
  display: flex;
  align-items: center;
  padding: 0 10px;

  position: relative;
  z-index: 1;
}

.back-icon {
  width: 24px;
  height: 24px;
  cursor: pointer;
  margin-left: 5px;
}



/* 添加标题容器样式 */
.title-container {
  padding: 0px;
  padding-bottom: 0px;
  padding-left: 25px;
  background: #ffffff;
}

.page-title {
  font-family: "SourceHanFontBold";
  font-size: 24px;
  color: #333333;
  margin: 0;
}

/* 调整列表容器样式以适应新布局 */
.history-list {
  flex: 1;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  height: calc(100vh - 56px - 64px);
  background: #ffffff;
}

.content-wrapper {
  min-height: calc(100% + 40px);
  padding-top: 40px;
  margin-top: -40px;
  position: relative;
  background: #ffffff;
}

.cards-container {
  transition: transform 0.3s cubic-bezier(0.23, 1, 0.32, 1);
  will-change: transform;
  padding: 16px;
  position: relative; /* 添加相对定位 */
}

.refresh-area {
  position: absolute;
  top: -30px;
  left: 0;
  right: 0;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #ffffff;
  color: #666;
  font-size: 14px;
}

.loading-area {
  padding: 15px 0;
  margin-bottom: 100px;
  text-align: center;
  color: #666;
  font-size: 14px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 添加空状态样式 */
.empty-state {
  text-align: center;
  padding: 40px 0;
  color: #999;
  font-size: 14px;
}

/* 添加弹窗样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog-content {
  width: 75%;
  max-width: 320px;
  min-height: 180px;
  background: white;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  flex-direction: column;
  animation: dialogFadeIn 0.3s ease-out;
}

.dialog-content h1,
.dialog-content h3 {
  text-align: center;
  margin: 0;
  padding: 10px 0;
  color: #333;
  font-size: 18px;
  font-weight: normal;
}

.dialog-content p {
  flex: 1;
  text-align: center;
  margin: 8px 0;
  color: #666;
  font-size: 15px;
  line-height: 1.5;
  display: flex;
  align-items: center;
  justify-content: center;
}

.dialog-buttons {
  display: flex;
  gap: 12px;
  padding-top: 15px;
  margin: 0;
}

.btn-action {
  flex: 1;
  height: 40px;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: normal;
  cursor: pointer;
  transition: all 0.2s ease;
}

.btn-action:not(.complete) {
  background-color: #f5f5f5;
  color: #666;
}

.btn-action.complete {
  background-color: #a5b2e5;
  color: white;
}

@keyframes dialogFadeIn {
  from {
    opacity: 0;
    transform: scale(0.95);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

/* 移动端适配 */
@media screen and (max-width: 480px) {
  .dialog-content {
    width: 85%;
    padding: 16px;
  }
}
</style>